package com.jcooky.tutorfs.proxy.processor;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcooky.tutorfs.proxy.Attributes;
import com.jcooky.tutorfs.proxy.filesystem.AbstractFileSystem;
import com.jcooky.tutorfs.proxy.filesystem.FileSystemException;
import com.jcooky.tutorfs.proxy.protocol.AbstractMessage;
import com.jcooky.tutorfs.proxy.protocol.ReqRead;
import com.jcooky.tutorfs.proxy.protocol.ResRead;

public class ReqReadProcessor implements MessageProcessor<ReqRead> {
	private static final Logger logger = LoggerFactory.getLogger(ReqReadProcessor.class);
	
	public void process(IoSession session, ReqRead message) throws ProcessException {
		logger.info("BEGIN - ReqRead processing");
		AbstractFileSystem fs = (AbstractFileSystem)session.getAttribute(Attributes.FILE_SYSTEM);
		ResRead resRead = (ResRead)AbstractMessage.getMessage(AbstractMessage.TYPE_RES_READ);
		IoBuffer sendBuffer = IoBuffer.allocate(resRead.length(), true);
		try {
			byte[] data = fs.read(message.getFilepath(), message.getPos(), message.getSize());
			resRead.setData(data);
			resRead.setSize(message.getSize());
		} catch(FileSystemException e) {
			resRead.setData(new byte[256]);
			resRead.setSize(-1);
			throw new ProcessException(e);
		} finally {
			sendBuffer.clear();
			resRead.toBytes(sendBuffer);
			sendBuffer.flip();
			session.write(sendBuffer);
		}
		
		logger.info("  END - ReqRead processing");
	}
}
